package com.example.mywanandroid.ui.bottom.project;

import androidx.fragment.app.Fragment;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.ViewModelProvider;
import androidx.viewpager.widget.ViewPager;

import com.example.mywanandroid.R;
import com.example.mywanandroid.base.BaseFragment;
import com.example.mywanandroid.bean.responsebean.WeChatBean;
import com.example.mywanandroid.databinding.FragmentProjectViewPagerBinding;
import com.example.mywanandroid.navinterface.ScrollToTop;
import com.example.mywanandroid.ui.adapter.FmPagerAdapter;
import com.example.mywanandroid.ui.articlelist.ArticleListFragment;

import java.util.ArrayList;
import java.util.List;

public class ProjectFragment extends BaseFragment<FragmentProjectViewPagerBinding,ProjectViewModel> implements ScrollToTop {

    private FmPagerAdapter adapter;

    @Override
    protected int getLayoutResId() {
        return R.layout.fragment_project_view_pager;
    }

    @Override
    protected void initViewModel() {
        mViewModel = new ViewModelProvider(this).get(ProjectViewModel.class);
    }

    @Override
    protected void bindViewModel() {
        mDataBinding.setViewModel(mViewModel);
    }

    @Override
    protected void init() {
        mViewModel.loadProjectList();

        addObserver();
    }

    @Override
    protected boolean isSupportLoad() {
        return true;
    }

    private void addObserver() {
        mViewModel.getDataList().observe(this,weChatBeans ->
            initViewPager(weChatBeans)
        );
    }

    private void initViewPager(List<WeChatBean> weChatBeans) {
        List<Fragment> fragments = new ArrayList<>();
        List<String> titles = new ArrayList<>();

        for (WeChatBean project : weChatBeans) {
            mDataBinding.tabLayout.addTab(mDataBinding.tabLayout.newTab().setText(project.getName()));
            titles.add(project.getName());
            fragments.add(ArticleListFragment.newInstance(2,project.getId()));
        }

        mDataBinding.tabLayout.setupWithViewPager(mDataBinding.viewPager);
        adapter = new FmPagerAdapter(getChildFragmentManager(), fragments,titles);
        mDataBinding.viewPager.setAdapter(adapter);
    }

    @Override
    public void scrollToTop() {
        ArticleListFragment currentFragment = (ArticleListFragment) adapter.getCurrentFragment();
        currentFragment.scrollToTop();
    }
}
